<style scoped>
.input-radio_switch{position: relative;}
.readonly-mask{position: absolute;left: 0;top: 0;width: 100%;height: 100%;z-index: 2;}
</style>
<template>
  <van-field v-bind="$attrs"
             :placeholder="placeholder"
             :model-value="content"
             readonly >
    <template #input>
      <input v-if="!is_info" type="hidden" :name="name" :value="modelValue">
      <van-switch :disabled="is_info" v-model="checked" @change="change" />
    </template>
  </van-field>
</template>

<script>
import s94 from "s94-js";
import {decode_config} from "@/js/s94_tool.js";

export default {
  name: "radio_switch",
  props: {
    name: String,
    modelValue: [String,Number],
    config: [String,Object],
    placeholder: String,
    is_info: Boolean,
  },
  emits: ['update:modelValue','change'],
  data(){
    return {
      need_display: true, //定义当modelValue变动时是否需要渲染，用来阻止当前组件变动 modelValue 后重新渲染
      options: [],
      content: "",
      checked: false,
      option_arr: [],
    }
  },
  methods: {
    display(){
      let options = decode_config(this.config || ["否", "是"]);
      this.options = options;
      let checked_value = options[1]?.value;
      this.checked = checked_value === s94.to_string(this.modelValue);
    },
    change(v){
      let i = v ? 1 :0;
      let val = this.options[i]["value"];
      this.need_display = false;
      setTimeout(()=>{this.need_display=true},10)
      this.$emit('update:modelValue', val);
      this.$emit('change', val);
    }
  },
  watch: {
    config(v){
      this.display();
    },
    modelValue(){
      if (this.need_display) this.display();
    },
  },
  mounted() {
    this.display();
  }
}
</script>